import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_ytx_plugin/src/flutter_ytx_plugin.dart';
import 'package:flutter_ytx_plugin/src/utils/screen_utils.dart';

class SearchOptions {
  Color backRoundColor;
  TextStyle? textStyle;
  TextStyle? hintTextStyle;
  String asset;
  Color? assetColor;
  Function? onSubmitted;
  Function? onKeyboardChanged;

  SearchOptions(
      {this.backRoundColor = Colors.white,
      this.textStyle,
      this.hintTextStyle,
      required this.asset,
      this.assetColor,
      this.onSubmitted,
      this.onKeyboardChanged});
}

final GlobalKey<_ContactsTemplateSearch> contactsTemplateSearchKey =
    GlobalKey<_ContactsTemplateSearch>();

class ContactsTemplateSearch extends StatefulWidget {
  SearchOptions searchOptions;

  ContactsTemplateSearch({super.key, required this.searchOptions});

  @override
  State<StatefulWidget> createState() => _ContactsTemplateSearch();
}

class _ContactsTemplateSearch extends State<ContactsTemplateSearch>
    with WidgetsBindingObserver {
  TextEditingController searchController = TextEditingController();
  FocusNode searchFocusNode = FocusNode();
  bool _keyboardVisible = false;
  bool _showClearButton = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    searchFocusNode.unfocus();
    searchController.addListener(() {
      setState(() {
        _showClearButton = searchController.text.isNotEmpty;
      });
    });
  }

  @override
  void dispose() {
    // 销毁
    WidgetsBinding.instance.removeObserver(this);
    if (searchController.hasListeners) {
      searchController.dispose();
    }
    if (searchFocusNode.hasFocus) {
      searchFocusNode.dispose();
    }
    searchFocusNode.unfocus();
    super.dispose();
  }

  // 监听
  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    FlutterView flutterView = PlatformDispatcher.instance.views.first;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {
        double bottomPadding = EdgeInsets.fromViewPadding(
          flutterView.viewInsets,
          flutterView.devicePixelRatio,
        ).bottom;

        //print("=======bottomPadding=======${bottomPadding}");
        if (bottomPadding > 100) {
          _keyboardVisible = true;
          _showClearButton = searchController.text.isNotEmpty;
        } else {
          // _showClearButton = false;
          _keyboardVisible = false;
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        searchFocusNode.requestFocus();
      },
      child: Container(
        height: 40.wpx,
        alignment: Alignment.center,
        margin: EdgeInsets.only(top: 10.hpx, left: 16.wpx, right: 16.wpx),
        decoration: BoxDecoration(
            color: widget.searchOptions.backRoundColor,
            borderRadius: BorderRadius.all(Radius.circular(8.wpx))),
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: [
            Center(
              child: IntrinsicWidth(
                stepWidth: !_keyboardVisible ? 0 : double.infinity - 15.wpx,
                // stepWidth: double.infinity - 15.wpx,
                child: TextField(
                  controller: searchController,
                  focusNode: searchFocusNode,
                  onEditingComplete: () {},
                  autofocus: false,
                  onSubmitted: (value) {
                    ///回调
                    searchFocusNode.unfocus();
                    widget.searchOptions.onSubmitted?.call(value);
                  },
                  textInputAction: TextInputAction.done,
                  style: widget.searchOptions.textStyle ??
                      TextStyle(
                        color: const Color(0xFF999999),
                        fontSize: 14.tpx,
                        fontWeight: FontWeight.w500,
                      ),
                  textAlignVertical: TextAlignVertical.center,
                  decoration: InputDecoration(
                    prefixIconConstraints: BoxConstraints(
                      maxWidth: 28.wpx,
                      maxHeight: 28.wpx,
                    ),
                    prefixIcon: Container(
                      margin: EdgeInsets.only(right: 5.wpx, left: 10.wpx),
                      alignment: Alignment.center,
                      child: Image.asset(
                        widget.searchOptions.asset,
                        width: 14.wpx,
                        height: 20.wpx,
                        color: widget.searchOptions.assetColor,
                      ),
                    ),
                    hintText: '搜索',
                    hintStyle: widget.searchOptions.hintTextStyle ??
                        TextStyle(
                          color: const Color(0xFF999999),
                          fontSize: 14.tpx,
                          fontWeight: FontWeight.w500,
                        ),
                    border: InputBorder.none,
                    // suffixIcon: _showClearButton
                    //     ? IconButton(
                    //   icon: Container(
                    //     width: 15.wpx,
                    //     height: 15.wpx,
                    //     decoration: BoxDecoration(
                    //         color: const Color(0xff999999),
                    //         borderRadius:
                    //         BorderRadius.all(Radius.circular(15.wpx))),
                    //     child: Icon(
                    //       Icons.clear,
                    //       color: Colors.white,
                    //       size: 10.wpx,
                    //     ),
                    //   ),
                    //   onPressed: () {
                    //     setState(() {
                    //       searchController.clear();
                    //       // _showClearButton = false;
                    //     });
                    //     searchFocusNode.unfocus();
                    //     widget.searchOptions.onSubmitted?.call("");
                    //   },
                    // )
                    //     : null,
                  ),
                ),
              ),
            ),
            _showClearButton
                ? Positioned(
                    right: 0,
                    child: IconButton(
                      icon: Container(
                        width: 15.wpx,
                        height: 15.wpx,
                        decoration: BoxDecoration(
                            color: const Color(0xff999999),
                            borderRadius:
                                BorderRadius.all(Radius.circular(15.wpx))),
                        child: Icon(
                          Icons.clear,
                          color: Colors.white,
                          size: 10.wpx,
                        ),
                      ),
                      onPressed: () {
                        setState(() {
                          searchController.clear();
                          // _showClearButton = false;
                        });
                        searchFocusNode.unfocus();
                        widget.searchOptions.onSubmitted?.call("");
                      },
                    ),
                  )
                : SizedBox()
          ],
        ),
      ),
    );
  }
}
